import React, { Component } from 'react'
import './RecordForm.css'
import { submitRecord } from '../utils/Config'

export default class RecordForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date:'',
      title:'',
      amount:''
    }
  }

  handleChange (e) {
    // let a = {abc:'123'}
    // let bfunc = (cc) => {
    //   console.log(cc);
      
    // }
    // let ccc = (a, a['cd'] = '456', a)
    // bfunc(ccc)
    // let name , obj;
    // name = e.target.name;
    // this.setState((
    //   obj = {},
    //   obj[""+name] = e.target.value,
    //   obj
    // ));

    const { name, value } = e.target;
    this.setState({ [name]: value });
    
    // switch (name) {
    //   case 'date':
    //     this.setState({
    //       date: e.target.value
    //     });
    //     break;
    //   case 'title':
    //     this.setState({
    //       title: e.target.value
    //     });
    //     break;
    //   case 'amount':
    //     this.setState({
    //       amount: e.target.value
    //     });
    //     break;
    //   default:
    //     break;
    // }
  }

  valid () {
    return this.state.date && this.state.title && this.state.amount;
  }

  handleSubmit () {
    // updata 数据 提交
    // POST
    // this.state
    // 处理数据
    const body = {
      date: 1533519443,
      title: this.state.title,
      amount: Number.parseInt(this.state.amount,0)
    }
    submitRecord(body).then(
      response => {
        // console.log(response.data);
        this.props.handleNewRecord(response.data)
        this.setState({
          date: '',
          title: '',
          amount: '' 
        })
      }
    ).catch(
      error => console.log(error.message)
    );
  }
  
  render() {
    return (
      <div className="container mb-3">
        <div className="row">
          <div className="col-md-3 col-sm-6 col-xs-6 mb-1">
            <input type="text" placeholder="日期" name="date" value={this.state.date} onChange={this.handleChange.bind(this)}/>
          </div>
          <div className="col-md-3 col-sm-6 col-xs-6 mb-1">
            <input type="text" placeholder="内容" name="title" value={this.state.title} onChange={this.handleChange.bind(this)}/>
          </div>
          <div className="col-md-3 col-sm-6 col-xs-6 mb-1">
            <input type="text" placeholder="合计" name="amount" value={this.state.amount} onChange={this.handleChange.bind(this)}/>
          </div>
          <div className="col-md-3 col-sm-6 col-xs-6">
            <button className="btn btn-primary btn-nomal" onClick={this.handleSubmit.bind(this)} disabled={!this.valid()}>添加</button>
          </div>
        </div>
      </div>
    )
  }
}
